<?php
declare (strict_types = 1);

namespace app\model;

use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\model\relation\BelongsTo;

/**
 * @mixin \think\Model
 */
class ActivityStatistics extends BaseModel
{
    // 设置当前模型对应的数据表
    protected $name = 'activity_statistics';

    /**
     * 关联活动
     * @return BelongsTo
     */
    public function activity(): BelongsTo
    {
        return $this->belongsTo(Activity::class, 'activity_id')->withTrashed();
    }

    /**
     * 关联小程序
     * @return BelongsTo
     */
    public function applet(): BelongsTo
    {
        return $this->belongsTo(Applet::class, 'applet_id');
    }

    /**
     * 保存数据
     * @param PayRecord $payRecord
     * @param array $options
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function saveData(PayRecord $payRecord, array $options = []): bool
    {
        $date = $options['date'] ?? date('Y-m-d');
        //充值人数
        $rechargeUv = $options['recharge_uv'] ?? 1;
        //点击人数
        $clickUv = $options['click_uv'] ?? 1;
        //点击次数
        $clickCount = $options['click_count'] ?? 1;
        //充值总金额
        $rechargeAmount = $options['recharge_amount'] ?? 0;
        //退款总金额
        $refundAmount = $options['refund_amount'] ?? 0;
        //充值次数
        $rechargeCount = $options['recharge_count'] ?? 0;
        $info = self::where([
            'activity_id' => $payRecord->activity_id,
            'applet_id' => $payRecord->officialAccount->applet_id ?? 0,
            'date' => $date
        ])->find();
        if (!$info){
            $info = new self;
            $info->activity_id = $payRecord->activity_id;
            $info->applet_id = $payRecord->officialAccount->applet_id ?? 0;
            $info->date = $date;
        }
        $info->click_count = $clickCount;
        $info->recharge_uv = $rechargeUv;
        $info->recharge_amount = $rechargeAmount;
        $info->click_uv = $clickUv;
        $info->refund_amount = $refundAmount;
        $info->recharge_count = $rechargeCount;
        return $info->save();
    }
}
